package fr.utbm.gi.in56.database;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;

/**
 * Implementation of a servlet connection.
 * 
 * @author Adrien Hoffer & Tarik Belabbas
 */
@WebServlet( "/ConnectionServlet" )
public class ConnectionServlet extends HttpServlet
{
	/**
	 * Version number associated to the serializable class.
	 */
	private static final long	serialVersionUID	= 1L;

	/**
	 * The connection pool.
	 */
	ConnectionPool				pool;
	
	/**
	 * The pool key.
	 */
	private static String		PoolKey				=
		"fr.utbm.gi.in56.database.ConnectionServlet"; //$NON-NLS-1$


	/**
	 * Default constructor.
	 * 
	 * @see HttpServlet#HttpServlet()
	 */
	public ConnectionServlet()
	{
		super();
	}

	/**
	 * Gets a new pool and initializes it. 
	 * 
	 * @see javax.servlet.GenericServlet#init(javax.servlet.ServletConfig)
	 */
	@Override
	public void init( ServletConfig _config ) throws ServletException
	{
		try
		{
			super.init( _config );
			this.pool = new ConnectionPool();
			this.pool.initialize();
		}
		catch ( ServletException e )
		{
			System.out.println( "Could not initialize" ); //$NON-NLS-1$
		}
		ServletContext context = getServletContext();
		
		// Store the pool in the ServletContex
		context.setAttribute( ConnectionServlet.PoolKey, this.pool );
	}

	/**
	 * Closes all connections in the pool and removes the attribute from the
	 * ServletContext.
	 * 
	 * @see javax.servlet.GenericServlet#destroy()
	 */
	@Override
	public void destroy()
	{
		getServletContext().removeAttribute( ConnectionServlet.PoolKey );
		
		if ( this.pool != null )
		{
			this.pool.destroy();
		}
		
		super.destroy();
	}
	
	/**
	 * Returns the pool key.
	 * 
	 * @return the pool key
	 */
	public static String getPoolKey()
	{
		return ConnectionServlet.PoolKey;
	}
}
